/*
 * @Author: doing
 * @Date: 2023-08-09 21:04:24
 * @LastEditors: git config user.name && git config user.email
 * @LastEditTime: 2023-09-02 20:42:21
 * @FilePath: \background-management-system\src\store\index.js
 * @Description: 
 * 模块化状态管理器
 * Copyright (c) 2023 by 1540265624@qq.com, All Rights Reserved. 
 */
import { createStore, createLogger } from 'vuex';
import menus from './modules/menus.js';
import roles from './modules/roles.js';
import users from './modules/users.js';

import { getinfo } from '~/api/manager'
import {
    removeToken
} from '~/composables/auth'


//设置默认值
const getDefaultState = function(){
    return{
        name: '我是主模块',
        // 用户信息
        userList: {},
    
        // 侧边宽度
        asideWidth: "250px",
    
        menuList: [],
        ruleNames: []   
    }
}

const state = getDefaultState()

const getters = {
    text: (state, getters, rootState) => {

    }
}
const mutations = {
    // 展开/缩起侧边
    handleAsideWidth(state) {
        state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
    },
    // 记录用户信息
    SET_USERINFO(state, userList) {
        state.userList = userList
        console.log(state.userList)
    },
    SET_MENUS(state, menuList) {
        state.menuList = menuList
    },
    SET_RULENAMES(state, ruleNames) {
        state.ruleNames = ruleNames
    },
    RESET_STATE: (state) => {
        Object.assign(state, getDefaultState())
    },
}

const actions = {
    // 获取当前登录用户信息
    getinfo({ state, commit }) {
        return new Promise((resolve, reject) => {
            const uid = state.userList.uid
            // console.log(uid)
            getinfo(uid).then(res => {
                console.log(res)
                res = res.data.data
                commit("SET_MENUS", res.menuTreeList)
                commit("SET_RULENAMES", res.buttonList)
                resolve(res)
            }).catch(err => reject(err))
        })
    },
    // 退出登录
    logout({ commit }) {
        // 移除cookie里的token
        removeToken()
        // 清除当前用户状态 vuex
        commit("SET_USERINFO", {})
    },

    //移除token
    resetToken({ commit }) {
        return new Promise(resolve => {
          removeToken() 
          commit('RESET_STATE')
          resolve()
        })
      }
}


const debug = process.env.NODE_ENV !== 'production';

export default createStore({
    state,
    getters,
    mutations,
    actions,

    modules: {
        menus,
        roles,
        users
    },
    strict: debug,
    plugins: debug ? [createLogger()] : []
})